﻿using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Caching;

namespace Moonwish.Core.DataAccess
{
    public abstract class BusinessComponentBase<T>
    {
        private readonly string _dataProviderCacheKey;

        protected BusinessComponentBase(string dataProviderKey)
        {
            _dataProviderCacheKey = String.Format("DataProvider={0}", dataProviderKey);
            if (!MemoryCache.Default.Contains(_dataProviderCacheKey))
            {
                var dataPrvider = System.Configuration.ConfigurationManager.AppSettings[dataProviderKey];
                var assembly = Assembly.Load(dataPrvider);
                MemoryCache.Default[_dataProviderCacheKey] = assembly;
            }
        }

        /// <summary>
        /// 创建业务组件。
        /// </summary>
        /// <returns></returns>
        public T Create()
        {
            var interfaceName = typeof(T).FullName;
            var assembly = (Assembly)MemoryCache.Default[_dataProviderCacheKey];
            var type = assembly.GetTypes().FirstOrDefault(t => t.GetInterface(interfaceName) != null);
            if (type == null)
            {
                throw new InvalidOperationException(string.Format("程序集“{0}”中未找到实现“{1}”的类型。", assembly.GetName(), interfaceName));
            }
            return (T)assembly.CreateInstance(type.FullName);
        }
    }
}